import server_url from '../constants/server_url';
import { save_inurl, save_outurl, update_inurl, update_outurl, inactive_inurl,
    inactive_outurl, use_email, email_url_list, finish_email, del_email } from './api';

async function postRouter(ctx, next) {
    switch (ctx.path) {
        case server_url.in_url_save:
            await inurlSave(ctx);
            break;
        case server_url.out_url_save:
            await outurlSave(ctx);
            break;
        case server_url.in_url_update(ctx.params.id)[1]:
            await inurlUpdate(ctx);
            break;
        case server_url.out_url_update(ctx.params.id)[1]:
            await outurlUpdate(ctx);
            break;
        case server_url.out_url_inactive(ctx.params.id)[1]:
            await outurlInactive(ctx);
            break;
        case server_url.in_url_inactive(ctx.params.id)[1]:
            await inurlInactive(ctx);
            break;
        case server_url.email_list_use(ctx.params.id)[1]:
            await useEmail(ctx);
            break;
        case server_url.email_show:
            let post_data = await parsePostData(ctx);
            let list = await email_url_list({url:post_data.url});
            ctx.render('email_url_list', {list: list});
            break;
        case server_url.email_list_del(ctx.params.id)[1]:
            await delEmail(ctx);
            break;
    }

}

async function inurlSave(ctx) {
    const data = await parsePostData(ctx);
    let isSuccess = true;
    let err = null;
    try {
        let col = await save_inurl(data);
        await finish_email(col.url);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {msg:'保存成功'})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function outurlSave(ctx) {
    const data = await parsePostData(ctx);
    let isSuccess = true;
    let err = null;
    try {
        await save_outurl(data);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {msg: '保存成功'})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function inurlUpdate(ctx) {
    const data = await parsePostData(ctx);
    let isSuccess = true;
    let err = null;
    try {
        await update_inurl({_id: ctx.params.id}, data);
    } catch(e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {msg: '更新成功'})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function outurlUpdate(ctx) {
    const data = await parsePostData(ctx);
    let isSuccess = true;
    let err = null;
    try {
        await update_outurl({_id: ctx.params.id}, data);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {msg: '更新成功'})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function outurlInactive(ctx) {
    const data = await parsePostData(ctx);
    let isSuccess = true;
    let err = null;
    try {
        await inactive_outurl(ctx.params.id);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {msg: '更新成功'})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function inurlInactive(ctx) {
    const data = await parsePostData(ctx);
    let isSuccess = true;
    let err = null;
    try {
        await inactive_inurl(ctx.params.id);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {msg: '更新成功'})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function useEmail(ctx) {
    let isSuccess = true;
    let err = null;
    try {
        await use_email(ctx.params.id);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {})
    } else {
        makeResult(ctx, false, err, null);
    }
}

async function delEmail(ctx) {
    let isSuccess = true;
    let err = null;
    try {
        await del_email(ctx.params.id);
    } catch (e) {
        err = e.toString();
        isSuccess = false;
    }
    if (isSuccess) {
        makeResult(ctx, true, null, {})
    } else {
        makeResult(ctx, false, err, null);
    }
}


function makeResult(ctx, isok, err, data) {
    let result = new Object();
    result.isok = isok;
    if (isok) {
        result.data = data;
    } else {
        result.err = err;
    }
    ctx.body = result;
}



// 解析上下文里node原生请求的POST参数
function parsePostData( ctx ) {
    return new Promise((resolve, reject) => {
        try {
            let postdata = "";
            ctx.req.addListener('data', (data) => {
                postdata += data
            })
            ctx.req.addListener("end",function(){
                let parseData = parseQueryStr( postdata )
                resolve( parseData )
            })
        } catch ( err ) {
            reject(err)
        }
    })
}

// 将POST请求参数字符串解析成JSON
function parseQueryStr( queryStr ) {
    let queryData = {}
    let queryStrList = queryStr.split('&')
    for (  let [ index, queryStr ] of queryStrList.entries()  ) {
        let itemList = queryStr.split('=')
        if(itemList[1])
            itemList[1] = itemList[1].replace('+', ' ');
        queryData[ itemList[0] ] = decodeURIComponent(itemList[1])
    }
    return queryData
}

module.exports=postRouter;